2024.4.8 繰り返し計算におけるデータの保持【torch】
2024.4.8 繰り返し計算におけるデータの保持【numpy】と同様に、繰り返し計算の過程で得られたテンソルを2次元にのテンソルに格納する方法を示す。
code:p01.py
import torch as pt
hist = []
data = pt.tensor(
1,2,3,4,
dtype = pt.float,
requires_grad = True
)
for i in range(5):
hist.append(data.flatten()) # <---dataを1次元に変換し保持
print('### とりあえず表示(テンソルを要素に持つリスト)')
print(hist)
print('### stack関数を使って二次元化')
result1 = pt.stack(hist)
print(type(result1))
print(result1.shape)
print(result1)
print('### ndarray化')
result2 = result1.detach().numpy()
print(type(result2))
print(result2.shape)
print(result2)
結果
code:result.py
### とりあえず表示
[tensor(1., 2., 3., 4., requires_grad=True), tensor(1., 2., 3., 4., requires_grad=True), tensor(1., 2., 3., 4., requires_grad=True), tensor(1., 2., 3., 4., requires_grad=True), tensor(1., 2., 3., 4., requires_grad=True)]
### stack関数を使って二次元化
<class 'torch.Tensor'>
torch.Size(5, 4)
tensor([1., 2., 3., 4.,
1., 2., 3., 4.,
1., 2., 3., 4.,
1., 2., 3., 4.,
1., 2., 3., 4.], grad_fn=<StackBackward0>)
### ndarray化
<class 'numpy.ndarray'>
(5, 4)
[1. 2. 3. 4.
1. 2. 3. 4.
1. 2. 3. 4.
1. 2. 3. 4.
1. 2. 3. 4.]